package com.thiswhyme.openfeign.gson.adapter.requestparam;

import com.thiswhyme.openfeign.gson.ThiswhymeGsonBuilder;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.core.convert.converter.ConditionalGenericConverter;

import java.util.Collections;
import java.util.Set;

/**
 * @description: @RequestParam转换器object->json
 * @author: thiswhyme
 * @date: 2020/8/24
 */
public class ObjectToJsonRequestParamConverter implements ConditionalGenericConverter {

    public ObjectToJsonRequestParamConverter() {
        super();
    }

    @Override
    public Set<ConvertiblePair> getConvertibleTypes() {
        return Collections.singleton(new ConvertiblePair(Object.class, String.class));
    }

    @Override
    public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
        try {
            return ThiswhymeGsonBuilder.toJson(source);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public boolean matches(TypeDescriptor sourceType, TypeDescriptor targetType) {
        if(sourceType.hasAnnotation(RequestParamConverter.class)) {
            return true;
        }
        return false;
    }
}

